﻿/// <reference path="jquery.js" />
/// <reference path="svg.js" />

function polarToCartesian(centerX, centerY, radius, angleInDegrees) {
    var angleInRadians = angleInDegrees * Math.PI / 180.0;
    var x = centerX + radius * Math.cos(angleInRadians);
    var y = centerY + radius * Math.sin(angleInRadians);
    return [x, y];
}

var pv = {
    svg: $('svg#main'),
    groud: $('svg#main'),
    //offset: $("svg#main").offset(),
    offset: { left: 0, top: 50 },
    frameInterval: 20,
    wind: { x: 0, y: 0 },
    pause: false,
    setInterval: function (func, interval, opts) {
        opts = $.extend({ times: null }, opts || {});

        interval *= 1000;
        function recursive(func) {
            if (!pv.pause) {
                if (opts.times == null || opts.times > 0) {
                    if (opts.times)
                        opts.times--;
                    if (func())
                        return;
                }
                else
                    return;
            }

            setTimeout(function () { recursive(func); }, interval);
        }
        setTimeout(function () { recursive(func); }, interval);
    },

    setTimer: function (target, sec, func, termFunc) {
        //var opts = $.extend({ termFunc: function () { } }, opts || {});
        if (termFunc == null)
            termFunc = function () { };

        function recursiveFunction(time, func) {
            if (!pv.pause) {
                if (target && target.isAlive) {
                    if (time > 0 || time === null) {
                        var terminate = func(target);
                        if (terminate) {
                            termFunc();
                            return;
                        }

                        if (time)
                            time--;
                        setTimeout(function () { recursiveFunction(time, func); }, 20);
                    }
                    else {
                        termFunc();
                    }
                }
            }
            else
                setTimeout(function () { recursiveFunction(time, func); }, 20);
        }

        if (sec === null)
            recursiveFunction(null, func);
        else
            recursiveFunction(sec * 50, func);
    },

    isInVillage: function (poistion) { return poistion.x > 800; },
    isInAttchRange: function (poisition, range) {
        return poisition.x + range > 800;
    },
    isInBoundary: function (poistion) {
        var x = poistion.x; // +pv.offset.left;
        var y = poistion.y; // +pv.offset.top;
        return x > 0 && x < 1400 && y > 0 && y < 800;
    },
    attachPath: function (node, opts) {
        //node = 

        var radius = node.status.radius;
        var posi = node.DOM.getTranslate();
        var top = posi.y - radius;
        var bottom = posi.y + radius;

        if (posi.x < 400 - radius && ((posi.y > 300 - 60 - radius && posi.y < 300 + 60 + radius) || (top < 270 && bottom > 330))) {
            if (posi.y < 300)
                return geo.vectorDir({ x: 400 - posi.x, y: (300 - radius - 60) - posi.y });
            else
                return geo.vectorDir({ x: 400 - posi.x, y: (300 + radius + 60) - posi.y });
        }

        return 90;
    }
};

var tip = {
    fadeOut: function (txt, target, opts) {
        //target = $.extend(new PvNode(), target);

        opts = $.extend({ color: 'red' }, opts || {});
        var prompt = convertStringToSvg('<text class="unselectable message" fill="' + opts.color + '" stroke-width="0" stroke-dasharray="null" stroke-linejoin="null" stroke-linecap="null" font-size="22" font-family="serif" text-anchor="middle" xml:space="preserve" stroke="#000000"/>');
        prompt.text(txt);
        prompt.animate({ 'opacity': 0 }, 2000);
        prompt.setRotate(target.DOM.getRotate() * -1);

        prompt.isAlive = true;
        y = 0;
        pv.setTimer(prompt, 2, function () {
            y -= 0.5;
            prompt.attr("y", y);
        }, function () {
            prompt.remove();
        });
        target.DOM.append(prompt);
    },
    buff: function (svg, target, last, opts) {
        var node = target.createNode({ id: 'hover', svg: svg });
        pv.setInterval(function () {
            node.dispose();
        }, last, { times: 1 });
    },
    sound: function (sound, opts) {
        document.getElementById("sound").innerHTML = "<embed src='" + sound + "' hidden='true' autostart='true' loop='false'/>";
    },
    aoeRadius: function (center, radius) {
        var node = convertStringToSvg('<circle stroke="black" fill-opacity="0" r="' + radius + '"/>');

        pv.svg.prepend(node);
        node.setTranslate(center.x, center.y);
        node.animate({ 'opacity': 0 }, 1400, function () { node.remove(); });
    },
    cooldown:function (center, radius, sec, funcTerm) {
        
    },
    shatter: function (svg, x, y, opts) {
        var shatter = new Object();
        shatter.svg = svg;
        var node = pv.svg.createNode(shatter, "shatter", x, y);
        node.animate({ 'opacity': 0 }, 1000, function () { node.remove(); });

    }
};
tip._namespace = true;

var geo = {
    angle3p: function (pm, p1, p2) {
        var v1 = { x: p1.x - pm.x, y: p1.y - pm.y };
        var v2 = { x: p2.x - pm.x, y: p2.y - pm.y };

        var dis1 = Math.sqrt(v1.x * v1.x + v1.y * v1.y);
        var dis2 = Math.sqrt(v2.x * v2.x + v2.y * v2.y);

        var angle = (v1.x * v2.y - v2.x * v1.y) / (dis1 * dis2);

        return Math.asin(angle);
    },

    dist2p: function (p1, p2) {
        var x = p1.x - p2.x;
        var y = p1.y - p2.y;
        return Math.sqrt(x * x + y * y);
    },
    vectorLen: function (v) {
        return Math.sqrt(v.x * v.x + v.y * v.y);
    },
    vectorDir: function (v) {
        if (v.x === 0 && v.y === 0)
            return null;
        if (v.y === 0) {
            return v.x > 0 ? 90 : -90;
        }
        if (v.x == 0) {
            return v.y > 0 ? 180 : 0;
        }
        var angle = Math.atan(v.x / v.y * -1) * 180 / Math.PI;
        if (v.y < 0)
            return angle;
        else
            return angle + 180;
    },
    vectorNorm: function (v) {
        var length = Math.sqrt(v.x * v.x + v.y * v.y);
        return { x: v.x / length, y: v.y / length };
    },
    vectorAdd: function (v1, v2) {
        return { x: v1.x + v2.x, y: v1.y + v2.y };
    },
    vectorPerpLeft: function (v) {
        return { x: v.y, y: -v.x };
    },
    vectorPerpRight: function (v) {
        return { x: -v.y, y: v.x };
    }
};

function getPosition(e) {
    var posx = 0;
    var posy = 0;

    if (e.originalEvent && (e.originalEvent.touches || e.originalEvent.changedTouches)) {
        var touches = e.originalEvent.touches || e.originalEvent.changedTouches;

        posx = touches[0].pageX;
        posy = touches[0].pageY;
    }

    else {
        if (e.pageX || e.pageY) {
            posx = e.pageX;
            posy = e.pageY;
        }
        else if (e.clientX || e.clientY) {
            posx = e.clientX + document.body.scrollLeft
    			+ document.documentElement.scrollLeft;
            posy = e.clientY + document.body.scrollTop
    			+ document.documentElement.scrollTop;
        }
    }

    return { x: posx - pv.offset.left, y: posy - pv.offset.top };
}

$.fn.createNode = function (node, catagery, x, y, opts) {
    var target = $(this);
    opts = $.extend({
        rotation: 0,
        disposed: function () { }
    }, opts || {});

    var root = convertStringToSvg(node.svg);

    root.isAlive = true;
    root.dispose = function () {
        root.remove();
        root.isAlive = false;
        opts.disposed({});
        if (node.dispose) {
            if (node.dispose.after)
                node.dispose.after(root, {});
        }
    };

    root.status = node;
    root.attr("pv-type", node.id);
    root.attr("pv-cat", catagery);

    if (node.radius)
        root.attr("pv-radius", node.radius);

    root.setTranslate(x, y);
    if (opts.rotation)
        root.setRotate(opts.rotation);

    target.append(root);

    return root;
};